﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Daily;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Shared.Models.Trade;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
using log4net;
using Newtonsoft.Json.Converters;
using WatsonWebsocket;
using PlaceOrder_Core.QuanYi;
using PlaceOrder_Core.Services.Instances;
using System.Diagnostics;

namespace PlaceOrder_Core.Helper
{
    public class WebSocketHelper : IDisposable
    {
        private static string serverUri = $"{DataHelper.BaseConfig.WebSocketUrl}/websocket/{UserHelper.Token}";
        public void Dispose()
        {

        }
        private static WebSocket serverWebSocket; //服务端websocket
        private static WebSocket clientWebSocket; //客户端websocket

        private Thread ReceiveMessageThread;
        private Thread SendMessageThread;
        public WebSocketHelper()
        {
            ReceiveMessageThread = new Thread(new ThreadStart(OnReceiveEvent));
            SendMessageThread = new Thread(new ThreadStart(OnSendEvent));
        }

        private void OnSendEvent()
        {
           
        }

        private void OnReceiveEvent()
        {
            
        }

        private void StartServie()
        {


        }

        #region 全局
        public void SubscribeTradeData(string TsCode)
        {
            if (clientWebSocket == null)
            {
                //log.Info("Start WebSocket", "", "");
                clientWebSocket = new WebSocket(serverUri);
                clientWebSocket.OnMessage -= Trade_OnMessage;

                clientWebSocket.OnMessage += Trade_OnMessage;
                clientWebSocket.Connect();
            }


        }

        private void Trade_OnMessage(object? sender, MessageEventArgs e)
        {
            Debug.WriteLine(e.Data);
        }
        #endregion


        #region 委托事件定义
        public delegate void SubscribeAllBidEventHandle(string TsCode, List<BidHistory> Bids, int BidType);
        public event SubscribeAllBidEventHandle SubscribeAllBidEvent;
        #endregion


        #region 客户端处理相关
        public bool StartConnectToServer(string ServerIP, int ServerPort)
        {
            try
            {
                Uri uri = new Uri($"ws://{ServerIP}:{ServerPort}");
                clientWebSocket = new WebSocket(uri.ToString());

                // 事件处理
                clientWebSocket.OnOpen += (sender, e) => Client_ServerConnected(sender, e);//连接触发
                clientWebSocket.OnClose += (sender, e) => Client_ServerDisconnected(sender, e); // 断连触发
                clientWebSocket.OnMessage += (sender, e) => Client_MessageReceived(sender, e); //消息接收时触发

                // KeepAliveInterval 需要手动实现
                clientWebSocket.EmitOnPing = true;


                //连接到服务器
                clientWebSocket.Connect();
                return true;
            }
            catch (Exception ex)
            {

            }
            return false;
        }

        /// <summary>
        /// 连接时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Client_ServerConnected(object sender, EventArgs e)
        {
            
        }

        /// <summary>
        /// 断开连接时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Client_ServerDisconnected(object sender, CloseEventArgs e)
        {
            
        }

        /// <summary>
        /// 接收到消息时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Client_MessageReceived(object sender, MessageEventArgs e)
        {
            if (e.IsPing)
            {
                Console.WriteLine("Ping received.");
            }
            else
            {
                Console.WriteLine("Message received: " + e.Data);
            }
        }

        #endregion 


        #region 服务端处理相关

        #endregion
    }
}
